package com.example.teesystem.common.utils;
import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author pxr
 * @data 2022/5/5 15:10
 */

public class DocUtil {

    public static void saveWord(Map<String,Object> dataMap, HttpServletResponse response) throws IOException {
        //response.setContentType("application/pdf");
        String filename = "exam_report";
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".doc");
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
        configuration.setClassForTemplateLoading(DocUtil.class, "/");
        Template template = configuration.getTemplate("Templates/2.xml");
        InputStreamSource streamSource = createWord(template, dataMap);
        InputStream inputStream = streamSource.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while ((inputStream.read(bytes)) != -1) {
            outputStream.write(bytes);// 写入数据
        }
        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    public static InputStreamSource createWord(Template template, Map<String, Object> dataMap) {
        StringWriter out = null;
        Writer writer = null;
        try {
            out = new StringWriter();
            writer = new BufferedWriter(out, 1024);
            template.process(dataMap, writer);
            return new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
